import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Sku } from '../entities/sku.entity';

@Injectable()
export class SkuService {
  constructor(
    @InjectRepository(Sku)
    private skuRepository: Repository<Sku>,
  ) {}

  async create(createSkuDto: { title: string; price?: number }): Promise<Sku> {
    const sku = this.skuRepository.create(createSkuDto);
    return this.skuRepository.save(sku);
  }

  async findAll(): Promise<Sku[]> {
    return this.skuRepository.find();
  }

  async findOne(id: number): Promise<Sku> {
    const sku = await this.skuRepository.findOne({ where: { id } });
    if (!sku) {
      throw new NotFoundException(`SKU with ID ${id} not found`);
    }
    return sku;
  }

  async update(
    id: number,
    updateSkuDto: { title?: string; price?: number },
  ): Promise<Sku> {
    const sku = await this.findOne(id);
    Object.assign(sku, updateSkuDto);
    return this.skuRepository.save(sku);
  }

  async remove(id: number): Promise<void> {
    const result = await this.skuRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`SKU with ID ${id} not found`);
    }
  }
}
